﻿<%@ WebHandler Language="C#" Class="RbSkillTargetBoard" %>

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Collections;
using System.IO;

/**
 * Description: 热表厂技能矩阵统计看板
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2025.6.23
 */

public class RbSkillTargetBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    UserImage u = new UserImage();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject obj)
    {
        string sql = @"
SELECT e.employeeid,e.fullname,e.employeename,mp.liuwei,m.totalscore,f.factoryname || '/' || wc.workcentername || '/' || te.teamname orginfo
FROM rbskilltargetemp rst
LEFT JOIN employee e ON e.employeeid = rst.employeeid
LEFT JOIN sessionvalues sv ON sv.employeeid = e.employeeid
LEFT JOIN factory f ON f.factoryid = sv.factoryid
LEFT JOIN workcenter wc ON wc.workcenterid = sv.workcenterid
LEFT JOIN teamemployee tee ON tee.employeeid = e.employeeid
LEFT JOIN team te ON te.teamid = tee.teamid
LEFT JOIN rbskilltargetmaint rtm ON rtm.id = rst.rbskilltargetmaintid
LEFT JOIN (
  SELECT rt.employeeid,
         SUM(CASE WHEN rt.processvalue = 0 THEN 0 
              WHEN rt.processvalue = 25 THEN 1
              WHEN rt.processvalue = 50 THEN 2
              WHEN rt.processvalue = 75 THEN 3
              WHEN rt.processvalue = 100 THEN 4
         END) totalscore
  FROM rbskilltargetemp rt
  GROUP BY rt.employeeid
) m ON m.employeeid = rst.employeeid
LEFT JOIN mes_userimage_mapping mp ON mp.employeename = e.employeename
WHERE rst.isuse = 0";

        //组织架构
        if (obj["selectOrg"] != null && obj["selectOrg"].ToString() != "")
        {
            JArray selectOrg = JArray.Parse(obj["selectOrg"].ToString());
            if (selectOrg.Count == 3)
            {
                sql += string.Format(" AND te.teamid = '{0}'", selectOrg[2].ToString());
            }
            if (selectOrg.Count == 2)
            {
                sql += string.Format(" AND wc.workcenterid = '{0}'", selectOrg[1].ToString());
            }
            if (selectOrg.Count == 1)
            {
                sql += string.Format(" AND f.factoryid = '{0}'", selectOrg[0].ToString());
            }
        }

        //员工
        if (obj["fullname"] != null && obj["fullname"].ToString() != "")
        {
            sql += string.Format(" AND e.fullname LIKE '%{0}%'", obj["fullname"].ToString());
        }

        //指标名称
        if (obj["skilltargetname"] != null && obj["skilltargetname"].ToString() != "")
        {
            sql += string.Format(" AND rtm.skilltargetname LIKE '%{0}%'", obj["skilltargetname"].ToString());
        }

        //指标类型
        if (obj["skilltype"] != null && obj["skilltype"].ToString() != "")
        {
            sql += string.Format(" AND rtm.skilltype = '{0}'", obj["skilltype"].ToString());
        }

        sql += @"
GROUP BY e.employeeid,e.fullname,f.factoryname,wc.workcentername,te.teamname,m.totalscore,mp.liuwei,e.employeename order by m.totalscore desc";
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)obj["currentPage"], (int)obj["pageSize"]);
        DataTable dtResult = dto.DBTable;

        dtResult.Columns.Add("userimageurl", typeof(string));
        //查找用户头像信息
        dtResult = u.getUserImage(dtResult, "userimageurl", "employeename", "liuwei");

        int columnCount = dtResult.Columns.Count;

        //查询指标名称
        sql = @"
SELECT rtm.skilltargetname,rtm.skilltype
FROM rbskilltargetemp rst
INNER JOIN rbskilltargetmaint rtm ON rtm.id = rst.rbskilltargetmaintid
LEFT JOIN team te ON te.teamid = rtm.teamid
LEFT JOIN workcenter wc ON wc.workcenterid = te.workcenterid
LEFT JOIN factory f ON f.factoryid = wc.factoryid
WHERE rst.isuse = 0";

        //指标名称
        if (obj["skilltargetname"] != null && obj["skilltargetname"].ToString() != "")
        {
            sql += string.Format(" AND rtm.skilltargetname LIKE '%{0}%'", obj["skilltargetname"].ToString());
        }

        //指标类型
        if (obj["skilltype"] != null && obj["skilltype"].ToString() != "")
        {
            sql += string.Format(" AND rtm.skilltype = '{0}'", obj["skilltype"].ToString());
        }

        //组织架构
        if (obj["selectOrg"] != null && obj["selectOrg"].ToString() != "")
        {
            JArray selectOrg = JArray.Parse(obj["selectOrg"].ToString());
            if (selectOrg.Count == 3)
            {
                sql += string.Format(" AND rtm.teamid = '{0}'", selectOrg[2].ToString());
            }
            if (selectOrg.Count == 2)
            {
                sql += string.Format(" AND wc.workcenterid = '{0}'", selectOrg[1].ToString());
            }
            if (selectOrg.Count == 1)
            {
                sql += string.Format(" AND f.factoryid = '{0}'", selectOrg[0].ToString());
            }
        }

        sql += @"
GROUP BY rtm.skilltargetname,rtm.skilltype
ORDER BY rtm.skilltype";

        DataTable dtItem = dal.GetDataTable(sql);

        foreach (DataRow row in dtItem.Rows)
        {
            dtResult.Columns.Add(row["skilltargetname"].ToString(), typeof(object));
        }

        sql = @"
SELECT rtm.skilltargetname,rst.employeeid,e.fullname,rst.processvalue,rst.notes,rtm.skilltype
FROM rbskilltargetemp rst
INNER JOIN rbskilltargetmaint rtm ON rtm.id = rst.rbskilltargetmaintid
INNER JOIN employee e ON e.employeeid = rst.employeeid
WHERE rst.isuse = 0";
        //员工
        if (obj["fullname"] != null && obj["fullname"].ToString() != "")
        {
            sql += string.Format(" AND e.fullname LIKE '%{0}%'", obj["fullname"].ToString());
        }

        //指标名称
        if (obj["skilltargetname"] != null && obj["skilltargetname"].ToString() != "")
        {
            sql += string.Format(" AND rtm.skilltargetname LIKE '%{0}%'", obj["skilltargetname"].ToString());
        }
        DataTable dtSkillTargetEmp = dal.GetDataTable(sql);

        foreach (DataRow dr in dtResult.Rows)
        {
            for (int i = columnCount; i < dtResult.Columns.Count; i++)
            {
                string filter = string.Format("employeeid = '{0}' AND skilltargetname='{1}'", dr["employeeid"].ToString(), dtResult.Columns[i].ColumnName);
                DataRow[] drList = dtSkillTargetEmp.Select(filter);
                if (drList.Length > 0)
                {
                    SkillTypeObj skillObj = new SkillTypeObj(drList[0]["skilltype"].ToString(), drList[0]["processvalue"].ToString());
                    dr[dtResult.Columns[i].ColumnName] = skillObj;
                }
                else
                {
                    DataRow[] filterRows = dtItem.Select(string.Format("skilltargetname = '{0}'", dtResult.Columns[i].ColumnName));
                    if (filterRows.Length > 0)
                    {
                        SkillTypeObj skillObj = new SkillTypeObj(filterRows[0]["skilltype"].ToString(), "");
                        dr[dtResult.Columns[i].ColumnName] = skillObj;
                    }
                }
            }
        }

        dtResult.Columns.Remove("tttttrn");
        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }

        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    class SkillTypeObj
    {
        public string name { get; set; }
        public string value { get; set; }
        public SkillTypeObj(string name, string value)
        {
            this.name = name;
            this.value = value;
        }
    }
}